import os
import random
from datetime import datetime
from conf.settings import MEDIA_ROOT
from conf.config import IMAGE_DOMAIN


def rename_file(filename):
    """
    重命名文件
    :param filename:
    :return:
    """
    extension = filename.split('.')[-1]
    if not extension:
        return False

    file_path = datetime.now().strftime('%Y/%m/%d')

    fn = datetime.now().strftime('%Y%m%d%H%M%S')
    fn = fn + '_%s%s%s' % (str(random.randint(0, 9)), str(random.randint(0, 9)), str(random.randint(0, 9)))

    new_name = "%s.%s" % (fn, extension)

    return [file_path, new_name]


def create_file(files):
    """
    创建文件
    :param files:
    :return:
    """
    if not files:
        return False
    new_path = rename_file(files.name)

    try:
        new_name = new_path[0] + '/' + new_path[1]
        file_path = os.path.join(MEDIA_ROOT, new_path[0])
        file_name = os.path.join(MEDIA_ROOT, new_name)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        # 保存图片
        with open(file_name, 'wb+') as f:
            f.write(files.read())
            f.close()
        return [new_name, IMAGE_DOMAIN + new_name, file_path]

    except:
        return False
